<template>
  <div class="candidate-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="page-title">候选人管理</span>
          <el-button type="primary" @click="openAddCandidateDialog">新增候选人</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 120px">
            <el-option label="未开始" :value="1" />
            <el-option label="面试中" :value="2" />
            <el-option label="面试完成" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="职业">
          <el-input v-model="searchForm.position" placeholder="请输入职业" />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchCandidateList">查询</el-button>
          <el-button @click="resetSearchForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 候选人列表 -->
      <el-table :data="candidateList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" min-width="80" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="gender" label="性别" min-width="80" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="phone" label="电话" min-width="120" />
        <el-table-column prop="position" label="应聘职位" min-width="120" show-overflow-tooltip />
        <el-table-column prop="experience" label="工作经验" min-width="100">
          <template #default="scope">
            {{ scope.row.experience }}年
          </template>
        </el-table-column>
        <el-table-column prop="graduateSchool" label="毕业院校" min-width="150" show-overflow-tooltip />
        <el-table-column label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.interviewStatus)">
              {{ getStatusText(scope.row.interviewStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="resumePath" label="简历" min-width="120">
          <template #default="scope">
            <div v-if="scope.row.resumePath" class="resume-actions">
              <el-button 
                type="primary" 
                size="small"
                class="resume-btn view-btn"
                @click="previewResume(scope.row.resumePath)"
              >
                <el-icon><View /></el-icon>
                查看简历
              </el-button>
              <el-button 
                type="success" 
                size="small"
                class="resume-btn download-btn"
                @click="downloadResume(scope.row.resumePath)"
              >
                <el-icon><Download /></el-icon>
                下载简历
              </el-button>
            </div>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button 
                type="primary" 
                link
                class="operation-btn edit-btn"
                @click="openUpdateCandidateDialog(scope.row)"
              >
                <el-icon><Edit /></el-icon>
                <span class="btn-text">编辑</span>
              </el-button>
              <el-button 
                type="danger" 
                link
                class="operation-btn delete-btn"
                @click="deleteCandidate(scope.row.id)"
              >
                <el-icon><Delete /></el-icon>
                <span class="btn-text">删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增候选人对话框 -->
    <el-dialog 
      v-model="addCandidateDialogVisible" 
      title="新增候选人" 
      :width="isMobile ? '90%' : '50%'"
      class="candidate-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closeAddDialog"
    >
      <el-form 
        ref="addCandidateFormRef" 
        :model="addCandidateForm" 
        :rules="rules" 
        label-width="100px"
        status-icon
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addCandidateForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="addCandidateForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addCandidateForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addCandidateForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="应聘职位" prop="position">
          <el-input v-model="addCandidateForm.position" placeholder="请输入应聘职位" />
        </el-form-item>
        <el-form-item label="工作经验" prop="experience">
          <el-input-number v-model="addCandidateForm.experience" :min="0" :max="50" placeholder="请输入工作经验年限" />
        </el-form-item>
        <el-form-item label="毕业院校" prop="graduateSchool">
          <el-input v-model="addCandidateForm.graduateSchool" placeholder="请输入毕业院校" />
        </el-form-item>
        <el-form-item label="技能标签" prop="skills">
          <el-input 
            v-model="addCandidateForm.skills" 
            placeholder="请输入技能，用逗号分隔" 
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="备注信息" prop="notes">
          <el-input 
            v-model="addCandidateForm.notes" 
            placeholder="请输入备注信息" 
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="上传简历" prop="resume">
          <el-upload
              class="upload-demo"
              ref="upload"
            action="/api/upload"
            :auto-upload="true"
              :on-change="handleResumeChange"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
              :limit="1"
              :file-list="fileList"
            accept=".pdf,.doc,.docx"
            :data="{ candidateId: addCandidateForm.id || 0 }"
            :headers="{
              'Content-Type': 'multipart/form-data'
            }"
          >
            <template #trigger>
              <el-button type="primary">选取文件</el-button>
            </template>
          </el-upload>
          <div v-if="addCandidateForm.resumePath" class="mt-2">
            <div class="file-info">
              <span class="file-name">已上传：{{ getResumeFileName(addCandidateForm.resumePath) }}</span>
              <div class="file-actions">
                <el-button type="primary" link @click="previewResume(addCandidateForm.resumePath)">查看简历</el-button>
                <el-button type="primary" link @click="downloadResume(addCandidateForm.resumePath)">下载简历</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeAddDialog">取消</el-button>
        <el-button type="primary" @click="submitAddCandidate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改候选人对话框 -->
    <el-dialog 
      v-model="updateCandidateDialogVisible" 
      title="修改候选人" 
      width="50%" 
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closeUpdateDialog"
    >
      <el-form 
        ref="updateCandidateFormRef" 
        :model="updateCandidateForm" 
        :rules="rules" 
        label-width="100px"
        status-icon
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="updateCandidateForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="updateCandidateForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateCandidateForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="updateCandidateForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="应聘职位" prop="position">
          <el-input v-model="updateCandidateForm.position" placeholder="请输入应聘职位" />
        </el-form-item>
        <el-form-item label="工作经验" prop="experience">
          <el-input-number v-model="updateCandidateForm.experience" :min="0" :max="50" placeholder="请输入工作经验年限" />
        </el-form-item>
        <el-form-item label="毕业院校" prop="graduateSchool">
          <el-input v-model="updateCandidateForm.graduateSchool" placeholder="请输入毕业院校" />
        </el-form-item>
        <el-form-item label="技能标签" prop="skills">
          <el-input 
            v-model="updateCandidateForm.skills" 
            placeholder="请输入技能，用逗号分隔" 
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="备注信息" prop="notes">
          <el-input 
            v-model="updateCandidateForm.notes" 
            placeholder="请输入备注信息" 
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="面试状态" prop="interviewStatus">
          <el-select v-model="updateCandidateForm.interviewStatus" placeholder="请选择面试状态">
            <el-option label="未开始" :value="1" />
            <el-option label="面试中" :value="2" />
            <el-option label="面试完成" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="面试结果" prop="interviewResult">
          <el-select v-model="updateCandidateForm.interviewResult" placeholder="请选择面试结果">
            <el-option label="未通过" :value="0" />
            <el-option label="待定" :value="1" />
            <el-option label="通过" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传简历" prop="resume">
          <el-upload
              class="upload-demo"
              ref="updateUpload"
            action="/api/upload"
            :auto-upload="true"
              :on-change="handleUpdateResumeChange"
            :on-success="handleUpdateUploadSuccess"
            :on-error="handleUpdateUploadError"
              :limit="1"
              :file-list="updateFileList"
            accept=".pdf,.doc,.docx"
            :data="{ candidateId: updateCandidateForm.id }"
            :headers="{
              'Content-Type': 'multipart/form-data'
            }"
          >
            <template #trigger>
              <el-button type="primary">选取文件</el-button>
            </template>
          </el-upload>
          <div v-if="updateCandidateForm.resumePath" class="mt-2">
            <div class="file-info">
              <span class="file-name">已上传：{{ getResumeFileName(updateCandidateForm.resumePath) }}</span>
              <div class="file-actions">
                <el-button type="primary" link @click="previewResume(updateCandidateForm.resumePath)">查看简历</el-button>
                <el-button type="primary" link @click="downloadResume(updateCandidateForm.resumePath)">下载简历</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeUpdateDialog">取消</el-button>
        <el-button type="primary" @click="submitUpdateCandidate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 简历预览对话框 -->
    <el-dialog 
      v-model="previewDialogVisible" 
      title="简历预览" 
      width="80%" 
      :close-on-click-modal="false" 
      :close-on-press-escape="false"
      class="preview-dialog"
    >
      <div class="pdf-container">
        <iframe 
          v-if="previewUrl"
          :src="previewUrl"
          class="pdf-viewer"
          type="application/pdf"
        ></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import {
  getCandidates,
  addCandidate,
  updateCandidate,
  deleteCandidate as deleteCandidateApi,
  uploadResume as uploadResumeApi,
  previewResume as previewResumeApi,
  downloadResume as downloadResumeApi
} from "@/api/candidateApi.js";
import { ElMessage, ElLoading } from "element-plus";
import { View, Download } from '@element-plus/icons-vue';

const baseUrl = 'http://123.56.105.243:9091';

const candidateList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const addCandidateDialogVisible = ref(false);
const updateCandidateDialogVisible = ref(false);
const addCandidateFormRef = ref(null);
const addCandidateForm = reactive({
  name: "",
  gender: 1,
  email: "",
  phone: "",
  position: "",
  experience: 0,
  graduateSchool: "",
  skills: "",
  notes: "",
  resumePath: "",
  interviewStatus: 1,
  interviewResult: 0
});
const updateCandidateFormRef = ref(null);
const updateUpload = ref(null);
const updateFileList = ref([]);
const updateCandidateForm = reactive({
  id: null,
  name: "",
  gender: 1,
  email: "",
  phone: "",
  position: "",
  experience: 0,
  graduateSchool: "",
  skills: "",
  notes: "",
  resumePath: "",
  interviewStatus: 1,
  interviewResult: 0
});
const fileList = ref([]);
const upload = ref(null);

// 搜索表单
const searchForm = reactive({
  status: "",
  position: "",
  dateRange: null,
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  position: [{ required: true, message: '请输入应聘职位', trigger: 'blur' }],
  graduateSchool: [{ required: true, message: '请输入毕业院校', trigger: 'blur' }],
};

// 获取完整的简历URL
const getResumeUrl = (path) => {
  if (!path) return '';
  if (path.startsWith('http')) return path;
  return `${baseUrl}${path}`;
};

// 获取候选人列表
const fetchCandidateList = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      interviewStatus: searchForm.status || null,
      position: searchForm.position || null,
      startDate: searchForm.dateRange ? searchForm.dateRange[0] : null,
      endDate: searchForm.dateRange ? searchForm.dateRange[1] : null,
    };
    const response = await getCandidates(params);
    if (response.code === 200) {
      candidateList.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.msg || "获取候选人列表失败");
    }
  } catch (error) {
    ElMessage.error("获取候选人列表失败");
  }
};

// 分页切换
const handlePageChange = () => {
  fetchCandidateList();
};

// 打开新增候选人对话框
const openAddCandidateDialog = () => {
  // 重置表单
  resetAddForm();
  // 显示对话框
  addCandidateDialogVisible.value = true;
};

// 重置新增表单
const resetAddForm = () => {
  // 重置表单数据
  Object.assign(addCandidateForm, {
    name: "",
    gender: 1,
    email: "",
    phone: "",
    position: "",
    experience: 0,
    graduateSchool: "",
    skills: "",
    notes: "",
    resumePath: "",
    interviewStatus: 1,
    interviewResult: 0
  });
  
  // 重置文件列表
  fileList.value = [];
  
  // 重置表单验证
  if (addCandidateFormRef.value) {
    addCandidateFormRef.value.resetFields();
  }
  
  // 清空上传组件的文件列表
  if (upload.value) {
    upload.value.clearFiles();
  }
};

// 关闭新增对话框
const closeAddDialog = () => {
  addCandidateDialogVisible.value = false;
  resetAddForm();
};

// 提交新增候选人
const submitAddCandidate = async () => {
  if (!addCandidateFormRef.value) return;
  
  try {
    // 表单验证
    await addCandidateFormRef.value.validate();
    
    const candidateData = {
      name: addCandidateForm.name,
      gender: addCandidateForm.gender,
      email: addCandidateForm.email,
      phone: addCandidateForm.phone,
      position: addCandidateForm.position,
      experience: addCandidateForm.experience,
      graduateSchool: addCandidateForm.graduateSchool,
      skills: addCandidateForm.skills,
      notes: addCandidateForm.notes,
      interviewStatus: 1,
      interviewResult: 0,
      resumePath: addCandidateForm.resumePath
    };
    
    const response = await addCandidate(candidateData);
    if (response.code === 200) {
      ElMessage.success("新增候选人成功");
      closeAddDialog();
      // 重置分页到第一页
      currentPage.value = 1;
      // 重新获取列表数据
      await fetchCandidateList();
    } else {
      ElMessage.error(response.msg || "新增候选人失败");
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message);
    } else {
    ElMessage.error("新增候选人失败");
    }
  }
};

// 打开修改候选人对话框
const openUpdateCandidateDialog = (candidate) => {
  resetUpdateForm();
  Object.assign(updateCandidateForm, {
    id: candidate.id,
    name: candidate.name || "",
    gender: candidate.gender || 1,
    email: candidate.email || "",
    phone: candidate.phone || "",
    position: candidate.position || "",
    experience: candidate.experience || 0,
    graduateSchool: candidate.graduateSchool || "",
    skills: candidate.skills || "",
    notes: candidate.notes || "",
    resumePath: candidate.resumePath || "",
    interviewStatus: candidate.interviewStatus || 1,
    interviewResult: candidate.interviewResult || 0
  });
  updateCandidateDialogVisible.value = true;
};

// 重置修改表单
const resetUpdateForm = () => {
  Object.assign(updateCandidateForm, {
    id: null,
    name: "",
    gender: 1,
    email: "",
    phone: "",
    position: "",
    experience: 0,
    graduateSchool: "",
    skills: "",
    notes: "",
    resumePath: "",
    interviewStatus: 1,
    interviewResult: 0
  });
  updateFileList.value = [];
  if (updateCandidateFormRef.value) {
    updateCandidateFormRef.value.resetFields();
  }
  if (updateUpload.value) {
    updateUpload.value.clearFiles();
  }
};

// 关闭修改对话框
const closeUpdateDialog = () => {
  updateCandidateDialogVisible.value = false;
  resetUpdateForm();
};

// 提交修改候选人
const submitUpdateCandidate = async () => {
  if (!updateCandidateFormRef.value) return;
  
  try {
    // 表单验证
    await updateCandidateFormRef.value.validate();
    
    const candidateData = {
      id: updateCandidateForm.id,
      name: updateCandidateForm.name,
      gender: updateCandidateForm.gender,
      email: updateCandidateForm.email,
      phone: updateCandidateForm.phone,
      position: updateCandidateForm.position,
      experience: updateCandidateForm.experience,
      graduateSchool: updateCandidateForm.graduateSchool,
      skills: updateCandidateForm.skills,
      notes: updateCandidateForm.notes,
      interviewStatus: updateCandidateForm.interviewStatus,
      interviewResult: updateCandidateForm.interviewResult,
      resumePath: updateCandidateForm.resumePath
    };
    
    const response = await updateCandidate(updateCandidateForm.id, candidateData);
    if (response.code === 200) {
      ElMessage.success("修改候选人成功");
      closeUpdateDialog();
      // 重新获取列表数据
      await fetchCandidateList();
    } else {
      ElMessage.error(response.msg || "修改候选人失败");
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message);
    } else {
    ElMessage.error("修改候选人失败");
    }
  }
};

// 删除候选人
const deleteCandidate = async (id) => {
  try {
    await deleteCandidateApi(id);
    ElMessage.success("删除候选人成功");
    fetchCandidateList();
  } catch (error) {
    ElMessage.error("删除候选人失败");
  }
};

// 上传简历
const uploadResume = async () => {
  if (!fileList.value.length) {
    ElMessage.warning("请先选择文件");
    return;
  }
  const formData = new FormData();
  formData.append("file", fileList.value[0].raw);
  formData.append("candidateId", addCandidateForm.id || 0);
  try {
    const response = await uploadResumeApi(formData);
    if (response.code === 200) {
      addCandidateForm.resumePath = response.data;
    ElMessage.success("简历上传成功");
    } else {
      ElMessage.error(response.msg || "简历上传失败");
    }
  } catch (error) {
    ElMessage.error("简历上传失败");
  }
};

// 修改候选人上传简历
const uploadUpdateResume = async () => {
  if (!updateFileList.value.length) {
    ElMessage.warning("请先选择文件");
    return;
  }
    const formData = new FormData();
    formData.append("file", updateFileList.value[0].raw);
    formData.append("candidateId", updateCandidateForm.id);
  try {
    const response = await uploadResumeApi(formData);
    updateCandidateForm.resumePath = response.data;
    ElMessage.success("简历上传成功");
  } catch (error) {
    ElMessage.error("简历上传失败");
  }
};

// 简历文件选择变化
const handleResumeChange = (file) => {
  if (file.status === 'ready') {
    const formData = new FormData();
    formData.append("file", file.raw);
    formData.append("candidateId", addCandidateForm.id || 0);
    uploadResumeApi(formData)
      .then(response => {
        if (response.code === 200) {
          addCandidateForm.resumePath = response.data;
          ElMessage.success("简历上传成功");
        } else {
          ElMessage.error(response.msg || "简历上传失败");
        }
      })
      .catch(() => {
        ElMessage.error("简历上传失败");
      });
  }
};

// 修改候选人简历文件选择变化
const handleUpdateResumeChange = (file) => {
  if (file.status === 'ready') {
    const formData = new FormData();
    formData.append("file", file.raw);
    formData.append("candidateId", updateCandidateForm.id);
    uploadResumeApi(formData)
      .then(response => {
        if (response.code === 200) {
          updateCandidateForm.resumePath = response.data;
          ElMessage.success("简历上传成功");
        } else {
          ElMessage.error(response.msg || "简历上传失败");
        }
      })
      .catch(() => {
        ElMessage.error("简历上传失败");
      });
  }
};

// 重置搜索表单
const resetSearchForm = () => {
  searchForm.status = "";
  searchForm.position = "";
  searchForm.dateRange = null;
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return "未开始";
    case 2:
      return "面试中";
    case 3:
      return "面试完成";
    default:
      return "未知";
  }
};

// 获取状态标签的颜色
const getStatusTagType = (status) => {
  switch (status) {
    case 1:
      return "info";
    case 2:
      return "warning";
    case 3:
      return "success";
    default:
      return "info";
  }
};

// 上传成功回调
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    addCandidateForm.resumePath = response.data;
    ElMessage.success("简历上传成功");
  } else {
    ElMessage.error(response.msg || "简历上传失败");
  }
};

// 上传失败回调
const handleUploadError = () => {
  ElMessage.error("简历上传失败");
};

// 修改候选人上传成功回调
const handleUpdateUploadSuccess = (response) => {
  if (response.code === 200) {
    updateCandidateForm.resumePath = response.data;
    ElMessage.success("简历上传成功");
  } else {
    ElMessage.error(response.msg || "简历上传失败");
  }
};

// 修改候选人上传失败回调
const handleUpdateUploadError = () => {
  ElMessage.error("简历上传失败");
};

// 在 script setup 部分添加 getResumeFileName 方法
const getResumeFileName = (url) => {
  if (!url) return 'resume';
  // 从URL中提取文件名
  const fileName = url.split('/').pop();
  // 如果文件名包含查询参数，去除查询参数
  return fileName.split('?')[0];
};

// 预览简历
const previewDialogVisible = ref(false);
const previewUrl = ref('');

const previewResume = async (path) => {
  if (!path) return;
  
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在加载简历...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    const pdfUrl = getResumeUrl(path);
    if (!pdfUrl) {
      throw new Error('无效的PDF URL');
    }
    
    previewUrl.value = pdfUrl;
    previewDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('预览简历失败');
    console.error('预览错误:', error);
  } finally {
    loadingInstance.close();
  }
};

// 下载简历
const downloadResume = async (path) => {
  if (!path) return;
  
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在下载简历...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    const response = await downloadResumeApi(path);
    if (response.code === 200) {
      // 创建下载链接
      const link = document.createElement('a');
      link.href = response.data;
      link.download = getResumeFileName(path);
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      ElMessage.success('简历下载成功');
    } else {
      ElMessage.error(response.msg || '下载简历失败');
    }
  } catch (error) {
    ElMessage.error('下载简历失败');
    console.error('下载错误:', error);
  } finally {
    loadingInstance.close();
  }
};

// 添加移动端检测
const isMobile = computed(() => {
  return window.innerWidth <= 768
})

// 监听窗口大小变化
window.addEventListener('resize', () => {
  isMobile.value = window.innerWidth <= 768
})

onMounted(() => {
  fetchCandidateList();
});
</script>

<style scoped>
.candidate-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.box-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.box-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background-color: #409EFF;
  border-radius: 2px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper:focus-within),
:deep(.el-select__wrapper:focus-within) {
  box-shadow: 0 0 0 1px #409EFF inset;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  margin: 20px 0;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  height: 50px;
  padding: 8px 0;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table .cell) {
  padding: 0 8px;
  line-height: 1.5;
}

:deep(.el-tag) {
  margin: 0;
}

/* 确保按钮文字不会被截断 */
:deep(.el-table .cell) {
  white-space: nowrap;
}

/* 优化表格内容过长时的显示 */
:deep(.el-table .cell .el-tooltip__trigger) {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 优化tooltip样式 */
:deep(.el-tooltip__popper) {
  max-width: 300px;
  line-height: 1.5;
  padding: 8px 12px;
  font-size: 13px;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.operation-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
  background: none;
  border: none;
}

.operation-btn .el-icon {
  font-size: 16px;
}

.btn-text {
  font-size: 14px;
  line-height: 1;
}

.edit-btn {
  color: #409EFF;
  background: none !important;
  border: none !important;
  box-shadow: none !important;
}

.edit-btn:hover,
.edit-btn:focus {
  color: #66b1ff;
  background: none !important;
  border: none !important;
  box-shadow: none !important;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
  background: none;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.el-button--primary) {
  background-color: #409EFF;
  border-color: #409EFF;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
}

:deep(.el-button--default) {
  border-color: #dcdfe6;
}

:deep(.el-button--default:hover) {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 30px 20px;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

/* 文件上传区域样式 */
.file-info {
  margin-top: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
}

.file-name {
  display: block;
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.file-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.file-action-btn {
  color: #409EFF;
  background: none !important;
  border: none !important;
  box-shadow: none !important;
}

.file-action-btn:hover,
.file-action-btn:focus {
  color: #66b1ff;
  background: none !important;
  border: none !important;
  box-shadow: none !important;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  margin-top: 20px;
  justify-content: flex-end;
  padding: 0;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: 16px;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  transition: all 0.3s;
}

:deep(.el-pagination .el-pager li:not(.is-disabled).is-active) {
  background-color: #409EFF;
  color: #fff;
}

/* 上传组件样式优化 */
:deep(.el-upload-list) {
  margin-top: 8px;
}

:deep(.el-upload-list__item) {
  transition: all 0.3s;
  border-radius: 4px;
}

:deep(.el-upload-list__item:hover) {
  background-color: #f5f7fa;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 120px;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409EFF;
  background-color: #f5f7fa;
}

.resume-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.resume-btn {
  width: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 6px 12px;
  font-size: 13px;
  border-radius: 4px;
  transition: all 0.3s;
}

.view-btn {
  background-color: #409EFF;
  border-color: #409EFF;
}

.view-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
}

.download-btn {
  background-color: #67C23A;
  border-color: #67C23A;
}

.download-btn:hover {
  background-color: #85ce61;
  border-color: #85ce61;
  transform: translateY(-1px);
}

:deep(.el-icon) {
  margin-right: 2px;
  font-size: 14px;
}

/* 优化表格中的按钮样式 */
:deep(.el-table .cell) {
  padding: 8px 12px;
}

:deep(.el-table .el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
}

/* 预览对话框样式 */
:deep(.preview-dialog .el-dialog__body) {
  padding: 0;
  background-color: #f5f7fa;
}

:deep(.preview-dialog .el-dialog__header) {
  margin: 0;
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

:deep(.preview-dialog .el-dialog__title) {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

/* PDF预览样式 */
.pdf-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f5f7fa;
  padding: 20px;
  min-height: 600px;
}

.pdf-viewer {
  width: 100%;
  height: 600px;
  border: none;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .candidate-management {
    padding: 12px;
  }

  .search-form {
    padding: 12px;
  }

  .search-form :deep(.el-form-item) {
    margin-bottom: 12px;
  }

  .search-form :deep(.el-input__wrapper),
  .search-form :deep(.el-select) {
    width: 100%;
  }

  .operation-area {
    flex-direction: column;
    gap: 12px;
  }

  .operation-area .el-button {
    width: 100%;
  }

  .candidate-dialog :deep(.el-dialog__body) {
    padding: 16px;
  }

  .candidate-dialog :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  .candidate-dialog :deep(.el-form-item__label) {
    float: none;
    display: block;
    text-align: left;
    padding: 0 0 8px;
  }

  .candidate-dialog :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }

  .candidate-dialog :deep(.el-input__wrapper),
  .candidate-dialog :deep(.el-select),
  .candidate-dialog :deep(.el-input-number) {
    width: 100%;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }

  .dialog-footer .el-button {
    width: 100%;
  }

  .resume-actions {
    flex-direction: row;
    justify-content: center;
  }

  .resume-btn {
    width: auto;
  }
}
</style>